package com.authine.cloudpivot.ext.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.ext.mapper.HOrgDepartmentMapper;
import com.authine.cloudpivot.ext.model.DataDryingModel;
import com.authine.cloudpivot.ext.service.DataDryingService;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.util.DateUtils;
import com.google.common.collect.Maps;

import lombok.extern.slf4j.Slf4j;

/**
 * @author yifanggen
 * @version 1.0.0
 * @ClassName DataDryingServiceImpl.java
 * @Description
 * @Date: 2021/6/28
 */
@Service
@Slf4j
public class DataDryingServiceImpl implements DataDryingService {
    @Autowired
    private HOrgDepartmentMapper hOrgDepartmentMapper;

    @Autowired
    private DubboConfigService dubboConfigService;

    private String adminUserId = "2c9280a26706a73a016706a93ccf002b";

    @Override
    public void statistics(String deptId) {
        long currentTimeMillis = System.currentTimeMillis();
        List<String> ids = new ArrayList<>();
        // 保存数据
        Map<String, Object> modelData = Maps.newHashMap();
        List<String> deptIds = getDeptIds(deptId, ids);
        Integer village_total = 0;
        Integer activated_total = 0;
        Integer activated_households = 0;
        log.info("获取deptIds:" + deptIds);
        for (String sonId : deptIds) {
            List<UserModel> usersByDeptId = dubboConfigService.getOrganizationFacade().getUsersByDeptId(sonId);
            log.info("获取hOrgUsers:{}", usersByDeptId);
            if (usersByDeptId.size() > 1) {
                boolean flag = false;
                for (UserModel hOrgUser : usersByDeptId) {
                    // true 激活 false 未激活
                    village_total = village_total + 1;
                    if (hOrgUser.getActive()) {
                        activated_total = activated_total + 1;
                        flag = true;
                    }
                }
                if (flag) {
                    activated_households = activated_households + 1;
                }
            } else if (usersByDeptId.size() == 1) {
                village_total = village_total + 1;
                if (usersByDeptId.get(0).getActive()) {
                    activated_total = activated_total + 1;
                    activated_households = activated_households + 1;
                }
            }
            log.info("获取hOrgUsers结束");
        }
        getCityName(deptId, modelData);
        // 通讯录人数
        modelData.put(DataDryingModel.VILLAGE_TOTAL, village_total);
        // 激活总人数
        modelData.put(DataDryingModel.ACTIVATED_TOTAL, activated_total);
        // 激活率
        if (village_total > 0 && activated_total > 0) {
            BigDecimal activated_rate =
                new BigDecimal(activated_total * 100).divide(new BigDecimal(village_total), 4, 5);
            modelData.put(DataDryingModel.ACTIVATED_RATE, activated_rate);
        }
        // 户数
        Integer households = deptIds.size();
        modelData.put(DataDryingModel.HOUSEHOLDS, households);
        // 激活户数
        modelData.put(DataDryingModel.ACTIVATED_HOUSEHOLDS, activated_households);
        // 户激活率
        if (households > 0 && activated_households > 0) {
            BigDecimal activated_households_rate =
                new BigDecimal(activated_households * 100).divide(new BigDecimal(households), 4, 5);
            modelData.put(DataDryingModel.ACTIVATED_HOUSEHOLDS_RATE, activated_households_rate);
        }
        // 统计日期
        modelData.put(DataDryingModel.STATISTICE_DATE, DateUtils.getDate());
        BizObjectModel model = new BizObjectModel("data_drying", modelData, false);
        log.info("data_drying新增开始");
        String thisFormObjectId = dubboConfigService.getBizObjectFacade().saveBizObject(adminUserId, model, false);
        log.info("data_drying新增结束");
        long currentTimeMillis1 = System.currentTimeMillis();
        log.info("新增" + thisFormObjectId + "条，同步" + deptId + "总耗时:" + (currentTimeMillis1 - currentTimeMillis) + "ms");
    }

    private void getCityName(String deptId, Map<String, Object> modelData) {
        log.info("deptId：{}", deptId);
        DepartmentModel department = dubboConfigService.getOrganizationFacade().getDepartment(deptId);
        log.info("orgDepartment：{}", department);
        DepartmentModel rootDepartmentByCorpId =
            dubboConfigService.getOrganizationFacade().getRootDepartmentByCorpId(department.getCorpId());
        log.info("orgDepartment：{}", rootDepartmentByCorpId);
        try {
            // 市/县 乡/镇/街道
            String name = rootDepartmentByCorpId.getName();
            int i = 3;
            int i2 = name.indexOf("乡") > 0 ? name.indexOf("乡")
                : name.indexOf("镇") > 0 ? name.indexOf("镇") : name.indexOf("街道");
            int i3 = name.indexOf("街道") > 0 ? 2 : 1;
            // 市
            modelData.put(DataDryingModel.CITY, name.substring(0, i));
            // 镇
            modelData.put(DataDryingModel.TOWN, name.substring(i, i2 + i3));
            // 村
            modelData.put(DataDryingModel.VILLAGE, name.substring(i2 + i3));
            log.info("city：" + name.substring(0, i + 1) + " town:" + name.substring(i + 1, i2 + i3) + " village:"
                + name.substring(i2 + i3));
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    /**
     * @param id
     * @param list
     * @return java.util.List<java.lang.String>
     * @author liujing
     * @description: 递归获取部门最底层部门id集合
     * @date 2021/6/17
     */
    public List<String> getDeptIds(String id, List<String> list) {
        List<String> list1 = hOrgDepartmentMapper.getSonDeptIds(id);
        if (CollectionUtils.isEmpty(list1)) {
            list.add(id);
        } else {
            for (String s : list1) {
                getDeptIds(s, list);
            }
        }
        return list;
    }
}
